<template>
  <!-- 服务管理 -->
  <div class="innerPageTable-box-OneTwo value-set-list-wrap innerPageTable-out-flex">
    <!-- 搜索区域 -->
    <SelfAdaption>
      <Form
        :model="searchForm"
        ref="serviceForm"
        slot="adaption-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <Form-item prop="type" :label="'模板类型：'">
          <Select v-model="searchForm.type" clearable @on-change="onChange">
            <Option v-for="item in formType" :value="item.key" :key="item.key">{{ item.name }}</Option>
          </Select>
        </Form-item>
        <Form-item prop="name" :label="'表单名称：'">
          <Input
            type="text"
            clearable
            v-model.trim="searchForm.name"
            :placeholder="'请输入'"
            @on-enter="searchValueSet"
          ></Input>
        </Form-item>
        <Form-item prop="year" :label="'年份：'">
          <DatePicker type="year" :value="searchForm.year" @on-change="handleChange"></DatePicker>
        </Form-item>
        <Form-item prop="creator" :label="'创建人：'">
          <Input
            type="text"
            v-model.trim="searchForm.creator"
            :placeholder="'请输入'"
            @on-enter="searchValueSet"
          ></Input>
        </Form-item>
        <!-- 查询\重置按钮 -->
        <Form-item prop="button" class="search-solt-btn">
          <RPButton optType="search" ref="search" @click="searchValueSet" />
          <RPButton btnType="default" text="重置" @click="handleReset" />
        </Form-item>
      </Form>
    </SelfAdaption>
    <InnerPageTable ref="formTable" :config="pageTableConfig">
      <div slot="table-bar">
        <RPButton optType="create" type="info" text="新增表单" @click="createForm" />
        <RPButton optType="create" type="info" text="发布表单" :disabled="formPublishDisabled" @click="formPublish" />
        <RPButton optType="create" type="info" text="发起填报" :disabled="startFillDisabled" @click="startFill" />
        <RPButton optType="create" type="info" text="停止填报" :disabled="stopFillDisabled" @click="stopFill" />
        <RPButton optType="create" type="info" text="模板预览" @click="previewFormModal" />
        <Tooltip
          style="margin-left:20px"
          max-width="1000"
          content="1、【发起填报】之前必须先【发布表单】和【关联流程】，【发布表单】和【关联流程】无严格先后顺序
2、再次【发起填报】的前置条件为上一轮填报结束，即表单状态为“结束”，若表单状态不是“结束”，请先点击【停止填报】，再点击【发起填报】发起新一轮填报。"
        >
          <span style="color:#17233D">操作说明</span>
          <Icon type="ios-help-circle-outline" />
        </Tooltip>
      </div>
    </InnerPageTable>
  </div>
</template>

<script>
import {
  STATUS_TYPE_APPROVED,
  STATUS_TYPE_FINISH,
  STATUS_TYPE_PUBLISHED,
  STATUS_TYPE_TERMINATED
} from '@/views/formConst'
import { formType } from '@/views/formConst'
import { formColumns } from './columns'
import { FORM_TYPES } from './const/index'
import CreateFormModule from './components/CreateFormModule.vue'

import BindBpm from './components/BindBpm'
import previewType from './components/PreviewType.vue'
import formCenterApi from '../../api/formCenter.js'
import ApplyForm from './createForm/applyForm/index.vue'
import RateForm from './createForm/rateForm/index.vue'
import IndicatorForm from './createForm/indicatorForm/index.vue'
import TaskForm from './createForm/taskForm/index.vue'
import previewApplyForm from './writeForm/applyForm/index.vue'
import previewRateForm from './writeForm/rateForm/index.vue'
import StartFilling from './components/StartFilling'
import ReportHistory from './components/ReportHistory'
import { mapState } from 'vuex'
import { getBpmPage } from '@/views/common'
export default {
  // components: { IndicatorForm, TaskForm, ApplyForm, RateForm },
  data() {
    return {
      userCode: sessionStorage.userCode,
      formType: formType,
      isSelectForm: [],
      searchForm: {
        creator: '',
        type: '',
        year: '',
        name: '',
        updateBy: ''
      },
      pageTableConfig: {
        loadDataFn: this.getServiceList.bind(this),
        columns: formColumns.bind(this)(),
        autoFirst: true, //默认 就是 false, 要配置在这里
        onSelectionChange: this.onSelectionChange
      }
    }
  },
  computed: {
    ...mapState(['orgList', 'menuList', 'loginData']),
    formPublishDisabled() {
      return (
        this.isSelectForm.length <= 0 ||
        this.isSelectForm.filter(item => item.status != STATUS_TYPE_APPROVED).length > 0 ||
        this.isSelectForm.filter(item => item.createBy != this.userCode).length > 0
      )
    },
    startFillDisabled() {
      return (
        this.isSelectForm.length <= 0 ||
        this.isSelectForm.filter(item => item.status != STATUS_TYPE_FINISH && item.status != STATUS_TYPE_TERMINATED)
          .length > 0 ||
        this.isSelectForm.filter(item => item.createBy != this.userCode).length > 0
      )
    },
    stopFillDisabled() {
      return (
        this.isSelectForm.length <= 0 ||
        this.isSelectForm.filter(item => item.status != STATUS_TYPE_PUBLISHED).length > 0 ||
        this.isSelectForm.filter(item => item.createBy != this.userCode).length > 0
      )
    }
  },
  methods: {
    getServiceList(tableObj) {
      let { responseProcess, param } = tableObj
      formCenterApi
        .getFormPage({ ...param, ...this.searchForm, currentPage: param.commonPageDTO.currentPage })
        .then(res => {
          let { size, total, current, records, pages } = res.data.data
          responseProcess({
            pageNum: current,
            pageSize: size,
            pages: pages,
            records: records || [],
            total: total
          })
        })
    },
    handleChange(date) {
      this.searchForm.year = date
      this.searchValueSet()
    },
    onChange() {
      this.searchValueSet()
    },
    searchValueSet(isCurrent) {
      if (!isCurrent) {
        this.$refs['formTable'].currentPage = 1
      }
      this.$refs['formTable'].load(this.searchForm)
    },
    handleReset() {
      this.$refs['serviceForm'].resetFields()
      this.searchValueSet()
    },
    createForm() {
      new this.$pageModal(
        CreateFormModule,
        {
          props: {}
        },
        data => {
          data && this.searchValueSet(true)
        }
      )
    },
    previewFormModal() {
      new this.$pageModal(previewType, {
        props: {}
      })
    },
    startFill() {
      if (this.isSelectForm.length > 1) {
        this.$Message.error({
          content: '只能选择一条表单进行操作',
          duration: 2
        })
        return
      }
      const row = this.isSelectForm[0]
      //       （1）状态为已发布（校验不通过错误提示：“请发布表单”）
      // （2）完成流程配置（校验不通过错误提示：“请先完成流程配置”）
      if (row)
        new this.$pageModal(
          StartFilling,
          {
            props: { row }
          },
          data => {
            data && this.searchValueSet(true)
          }
        )
    },
    stopFill() {
      this.$confirm({
        type: 'success',
        title: '停止填报',
        content: '是否确认停止填报？'
      }).then(() => {
        const ids = this.isSelectForm.map(item => item.id)
        formCenterApi.formEnd({ idList: ids }).then(res => {
          if (res.data.code === 200) {
            this.$Message.success({
              content: '停止填报成功',
              duration: 2
            })
          } else {
            this.$Message.error({
              content: '停止填报失败',
              duration: 2
            })
          }
          this.searchValueSet(true)
        })
      })
    },
    formPublish() {
      this.$confirm({
        type: 'success',
        title: '发布表单',
        content: '是否确认发布表单？'
      }).then(() => {
        const ids = this.isSelectForm.map(item => item.id)
        formCenterApi.formPublish({ idList: ids }).then(res => {
          if (res.data.code === 200) {
            this.$Message.success({
              content: '发布成功',
              duration: 2
            })
          } else {
            this.$Message.error({
              content: '发布失败',
              duration: 2
            })
          }
          this.searchValueSet(true)
        })
      })
    },
    editForm(rowParam) {
      const formMapping = {
        // 0: IndicatorForm,
        0: ApplyForm,
        1: TaskForm,
        2: ApplyForm,
        3: RateForm
      }
      new this.$sidelipPage(
        formMapping[rowParam.type],
        {
          props: {
            row: rowParam
          }
        },
        data => {
          this.searchValueSet(true)
        }
      )
    },
    editBaseForm(rowParam) {
      new this.$pageModal(
        CreateFormModule,
        {
          props: {
            row: rowParam
          }
        },
        data => {
          data && this.searchValueSet(true)
        }
      )
    },
    copyForm(rowParam) {
      new this.$pageModal(
        CreateFormModule,
        {
          props: {
            row: rowParam,
            isCopy: true
          }
        },
        data => {
          data && this.searchValueSet(true)
        }
      )
    },
    deleteForm(rowParam) {
      this.$confirm({
        title: '删除',
        content: '当前表删除后不可撤回，您是否要继续删除?'
      }).then(() => {
        formCenterApi.formDelete([rowParam.id]).then(res => {
          if (res.data.code == 200) {
            this.$Message.success({
              content: '删除成功',
              duration: 3
            })
            this.searchValueSet()
          } else {
            this.$Message.error({
              content: res.data.msg || '删除失败',
              duration: 3
            })
          }
        })
      })
    },
    previewForm(rowParam) {
      const initAttr = {
        numberType: 0,
        scoreRequire: 1,
        type: 0,
        maxlength: 300,
        scoreDesReq: 0
      }
      const config = JSON.parse(rowParam.config)
      const formMapping = {
        [FORM_TYPES.APPLY]: previewApplyForm,
        [FORM_TYPES.RATE]: previewRateForm,
        [FORM_TYPES.INDICATOR]: previewApplyForm
      }
      const rowMapping = {
        [FORM_TYPES.APPLY]: {
          row: {
            name: rowParam.name,
            baseInfoList: config.baseInfoList,
            treeData: config.treeData,
            baseInfo: config.baseInfo,
            remark: rowParam.remark
          },
          isPreview: true
        },
        [FORM_TYPES.RATE]: {
          row: {
            treeData: config.treeData,
            baseInfo: { tip: config.baseInfo.tip, tipFile: config.baseInfo.tipFile }
          },
          rateTitle: rowParam.name,
          isPreview: true,
          attrs: config.treeData[0]?.attributes || initAttr
        },
        [FORM_TYPES.INDICATOR]: {
          row: {
            name: rowParam.name,
            baseInfoList: config.baseInfoList,
            treeData: config.treeData,
            baseInfo: config.baseInfo,
            remark: rowParam.remark
          },
          isPreview: true
        }
      }
      new this.$sidelipPage(formMapping[rowParam.type], {
        props: rowMapping[rowParam.type]
      })
    },
    configFormBpm(rowParam) {
      new this.$pageModal(
        BindBpm,
        {
          props: {
            formId: rowParam.id,
            row: rowParam
          }
        },
        data => {
          this.searchValueSet(true)
        }
      )
    },
    viewFormBpm(rowParam) {
      new this.$sidelipPage(
        getBpmPage(rowParam.type),
        {
          props: {
            id: rowParam.bpmpId,
            formId: rowParam.id
          }
        },
        data => {
          this.searchValueSet(true)
        }
      )
    },
    viewHistory(rowParam) {
      new this.$pageModal(
        ReportHistory,
        {
          props: {
            row: rowParam
          }
        },
        data => {}
      )
    },
    onSelectionChange(selection) {
      this.isSelectForm = selection
    }
  },
  async created() {
    if (!this.menuList || this.menuList.length === 0) {
      this.$store.dispatch('getMenuList')
    }
    if (this.orgList.length <= 0) {
      this.$store.dispatch('getOrgList')
    }
    if (Object.keys(this.loginData).length === 0) {
      await this.$store.dispatch('getLoginData')
    }
  }
}
</script>

<style lang="less" scoped>
// iview 固定表头横向滚动条穿透
/deep/.ivu-table-fixed-right {
  pointer-events: none;
}
/deep/.ivu-table-fixed-header {
  pointer-events: all;
}
/deep/.ivu-table-fixed-body {
  pointer-events: all;
}

/**动态计算高度，导致横向滚动条不出现，暂不知什么原因*/
// /deep/.ivu-table-wrapper {
//   height: calc(100vh - 285px) !important;
//   .ivu-table-body {
//     height: 100%;
//   }
// }
/deep/.table-bar button {
  &[disabled] {
    background: #f7f8fa;
    color: #b6b6b6;
    border-color: #f2f3f5;
  }

  &:last-child {
    color: #ffffff;
    background-color: var(--btn-primary-bg);
    border-color: var(--btn-primary-bg);

    &:hover {
      color: #ffffff;
    }
  }
}
</style>
